<template>

  <el-page-header @back="router.go(-1)" title="返回">
    <template #content>
      <span class="text-large font-600 mr-3">{{userForm.id?'编辑':'添加'}}员工</span>
    </template>
  </el-page-header>

  <div class="content">
    <el-form ref="userFormRef"
             style="max-width: 600px"
             :model="userForm"
             :rules="userFormRule"
             :inline="false"
             label-width="100px">

      <el-form-item label="账号:" prop="loginName">
        <el-input v-model="userForm.loginName" placeholder="请输入账号" maxlength="20"/>
      </el-form-item>

      <el-form-item label="姓名:" prop="name">
        <el-input v-model="userForm.name" placeholder="请输入姓名" maxlength="12"/>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleCancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>  
import { reactive } from "vue";  
import { useRoute, useRouter } from "vue-router";  
import { saveUser,findById } from "@/api/user";  
  
const router = useRouter();  
const route = useRoute();  
  
let userFormRef = reactive(null); // 假设这是某个表单引用，例如 Element Plus 的 el-form 的 ref  
  

//let userId = route.query.userId;  
  
let userForm = reactive({  
  id:null,
  name: null,  
  loginName: null,  
 
});  
  
let userFormRule = reactive({  
  name: [  
    {  
      required: true,  
      trigger: 'blur',  
      message: '请输入姓名', // 自定义的错误信息  
    }  
  ],  
  loginName: [  
    {  
      required: true,  
      trigger: 'blur' ,
      message: '请输入账号', // 自定义的错误信息 
    }  
  ],  
 
});  

if (route.query.userId) {
  // 根据id查找
  findById(route.query.userId).then(resp => {
    let user = resp.data;
    
    userForm.id = user.id;
    userForm.name = user.name;
    userForm.loginName = user.loginName;
    
  }).catch(error => {
    // 错误处理
  });
}
  
let handleSave = () => {  
  if (userFormRef && typeof userFormRef.validate === 'function') {  
    userFormRef.validate((valid) => {  
      if (valid) {  
        saveUser(userForm.id, userForm).then((resp) => {  
          if (resp.code === 200) { // 假设后端成功响应码为 200  
            router.push({ path: '/user/list' });  
            alert(resp.msg); // 显示成功消息  
          } else {  
            alert(resp.msg); // 显示错误信息  
          }  
        }).catch(error => {  
          console.error('请求失败:', error);  
          alert('请求失败，请稍后再试');  
        });  
      }  
    });  
  }  
};

let handleCancle = () => {  
  // 这里可以添加一些清理操作，比如重置表单等  
  // userForm = reactive({ name: '', loginName: '' }); // 如果需要重置表单  
  
  // 然后使用router.go(-1)回到上一个页面  
  router.go(-1);  
}  
</script>  
  
<style scoped>  
.content {  
  margin-top: 40px;  
}  
</style>

<style scoped>
.content {
  margin-top: 40px;
}
</style>
